<?php

namespace app\common\model\ads;

use think\Model;
use app\common\model\ads\Ad;
use app\common\service\Amount;
use fast\Random;

class Order extends Model
{

    // 表名
    protected $name = 'self_ad_order';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = false;
    protected $deleteTime = false;
   

    public function getStatusList()
    {
        return ['0' => "待支付", '1' => "已支付"];
    }

    public function getStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['status']) ? $data['status'] : '');
        $list = $this->getStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public static function createOrder($adId, $effecttime = 0, $toptime = 0, $recommendtime = 0){
        $ad = Ad::find($adId);
        if(!$ad){
            throw new \Exception('广告不存在');
        }
        
        $order = self::where('ad_id',$adId)->find();

        if($order){
            return $order;
        }

        if(!$effecttime && $ad['effecttime']){
            $effecttime = $ad->effecttime_day;
        }
 
        if(!$toptime && $ad['toptime']){
            $toptime = $ad->toptime_day;
        }

        if(!$recommendtime && $ad['recommendtime']){
            $recommendtime = $ad->recommendtime_day;
        }

        try {
            $ad_order['ad_id'] = $ad['id'];
            $ad_order['user_id'] = $ad['user_id'];
            $ad_order['money_amount'] = $ad['money_amount'];
            $ad_order['exp_fee'] = Amount::getAdExpFee($effecttime);
            $ad_order['service_fee'] = Amount::getAdSerFee($ad['money_amount']);
            $ad_order['top_fee'] = Amount::getAdTopFee($toptime);
            $ad_order['recom_fee'] = Amount::getAdRecFee($recommendtime);
            $ad_order['real_amount'] = Amount::getAdTotalFee($ad_order);
            $ad_order['status'] = 0;
            $ad_order['createtime'] = time();
            $ad_order['order_no'] = 'ad' . date('ymdhi') . Random::numeric(8);
        } catch (\Exception $e) {
            return null;
        }

        if( $ad_order['real_amount'] <= 0){
            return false;
        }
        
        return self::create($ad_order);
    }
}
